//
//  UIViewController+loading.m
//  LZNeiHan
//
//  Created by 梁梓烽 on 16/10/7.
//  Copyright © 2016年 liangzifeng. All rights reserved.
//

#import "UIViewController+loading.h"
#import <objc/runtime.h>

@interface UIViewLoadingView : UIView
@property(nonatomic,weak)UILabel *label;
@property(nonatomic,weak)UIActivityIndicatorView *indicatorView;
@end

@implementation UIViewLoadingView


-(UILabel *)label
{
    if (!_label) {
        UILabel *label = [[UILabel alloc]init];
        self.label = label;
        label.font =kFont(13);
        label.textColor = kTextColor;
        [self addSubview:label];
        label.text = @"正在加载...";
        
    }
    
    return _label;
}

-(UIActivityIndicatorView *)indicatorView
{
    if (!_indicatorView) {
        UIActivityIndicatorView *indicatiorView = [[UIActivityIndicatorView alloc]init];
        self.indicatorView  =  indicatiorView;
        [self addSubview:indicatiorView];
    }
    
    return _indicatorView;
}


-(void)startAnimation
{
    [self.indicatorView startAnimating];
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    
    self.label.frame = CGRectMake(self.width / 2.0 - 30, self.height / 2.0 - 40, 80, 40);
    self.indicatorView.frame = CGRectMake(self.width / 2.0 - 70, self.label.y, 40, 40);
}

@end




static const char loadingViewKey;
@implementation UIViewController (loading)

-(UIViewLoadingView *)loadingView
{
   return  (UIViewLoadingView *)objc_getAssociatedObject(self, &loadingViewKey);
}


-(void)setLoadingView:(UIViewLoadingView *)loadingView
{
    objc_setAssociatedObject(self, &loadingViewKey, loadingView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(void)showLoadingView{
    
    [self showLoadingViewWithFrame:CGRectMake(0, 0, kScreenWidth, 44)];
}

-(void)showLoadingViewWithFrame:(CGRect)frame
{
    //创建 持有 设置属性 添加 给frame
    UIViewLoadingView *loadingView = [UIViewLoadingView new];
    self.loadingView = loadingView;
    [self.view addSubview: loadingView];
    loadingView.frame = frame;

    self.loadingView.center = self.view.center;
    self.loadingView.centerY = self.view.centerY -30;
    
    [self.loadingView startAnimation];
    
}

-(void)hideLoadingView
{
    if (self.loadingView) {
        [self.loadingView removeFromSuperview];
    }
}
@end
